import { DirUtil } from "./DirUtil";
import { Main } from "../Main";
import { ShellUtil } from "./ShellUtil";

/**
 * 同步单个配置文件，到前端和后端
 */
export class SyncCfgUtil {
    static exec(cfgName:string, cb:()=>void) {
        console.log("cfgName", cfgName);
        let cfgFilePath = this.getCfgPath(cfgName, Main.projPath + "config/");
        console.log("cfgFilePath", cfgFilePath);
        let clientCfgFilePath = this.getCfgPath(cfgName, Main.codePath + "Resources/src/app/config/");
        console.log("clientCfgFilePath", clientCfgFilePath);
        let serverCfgFilePath = this.getCfgPath(cfgName, Main.projPath + "serverconfig/");
        console.log("serverCfgFilePath", serverCfgFilePath);
        ShellUtil.exec(`
cp -f ${cfgFilePath} ${clientCfgFilePath} || exit 1
cp -f ${cfgFilePath} ${serverCfgFilePath} || exit 1
        `,cb);
    }
    /**
     * 根据配置文件，找到绝对路径
     * @param cfgName 配置文件名，不带扩展名
     * @param dirPath 要查找的目录
     */
    private static getCfgPath(cfgName:string, dirPath:string):string {
        let files = DirUtil.getAllFile(dirPath);
        for (let i = 0; i < files.length; i++) {
            const file = dirPath + files[i];
            if (file.endsWith("/" + cfgName + ".lua")) {
                return file;
            }
        }
        console.log("无此配置", cfgName);
        console.log("输入的配置名，请不要输入扩展名。如果是新配置文件，请先由程序手动添加，后面才能使用自动同步的功能");
        throw new Error("找不到配置文件");
    }
}